package com.grad.webstudy.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.grad.webstudy.context.UserContext;
import com.grad.webstudy.dao.CollectDao;
import com.grad.webstudy.enums.StatusEnums;
import com.grad.webstudy.model.Collect;
import com.grad.webstudy.model.User;
import com.grad.webstudy.service.CollectService;
import com.grad.webstudy.service.CourseService;
import com.grad.webstudy.vo.CollectVo;
import com.grad.webstudy.vo.CourseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Description:
 * @Author: zjf
 * @Date: 2020/2/4 16:45.
 */
@Service
@Transactional
public class CollectServiceImpl implements CollectService {

    @Autowired
    private CollectDao collectDao;

    @Autowired
    private CourseService courseService;


    @Override
    public boolean addCollect(int courseId) {

        User login = UserContext.getLoginUser();
        return collectDao.insert(new Collect.Builder()
                .setUserId(login.getId())
                .setCourseId(courseId).build()) > 0;
    }

    @Override
    public PageInfo queryCollectByPage(int currPage, int pageSize) {
        User login = UserContext.getLoginUser();
        Page page = PageHelper.startPage(currPage, pageSize);
        PageInfo<CollectVo> result = new PageInfo<>(transToVo(collectDao.queryAll(login.getId())));


        result.setTotal(page.getTotal());
        result.setPageNum(currPage);
        result.setPageSize(pageSize);
        return result;
    }

    @Override
    public boolean deleteCollects(String deleteIds) {
        User login = UserContext.getLoginUser();
        List<String> deleteIdsList = Arrays.asList(deleteIds.split(","));
        return collectDao.deleteCollects(login.getId(), deleteIdsList) == deleteIdsList.size();
    }



    private List<CollectVo> transToVo(List<Collect> collects){
        List<CollectVo> result = new ArrayList<>();

        for (Collect collect : collects) {
            CollectVo collectVo = new CollectVo();
            CourseVo courseVo = courseService.queryById(collect.getCourseId(), StatusEnums.ONLINE.getStatus());
            collectVo.setId(collect.getId());
            collectVo.setUserId(collect.getUserId());
            collectVo.setCourseId(collect.getCourseId());
            collectVo.setClassName(courseVo.getClassName());
            collectVo.setCoverPath(courseVo.getCoverPath());
            result.add(collectVo);
        }
        return result;

    }
}
